package com.p2p.user.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.p2p.common.base.BaseController;
import com.p2p.common.cache.CacheManager;
import com.p2p.common.constants.Message;
import com.p2p.common.enums.ResponseEnum;
import com.p2p.common.utils.PageUtil;
import com.p2p.common.utils.ParamUtils;
import com.p2p.common.utils.ResMessage;
import com.p2p.common.utils.StringUtils;
import com.p2p.user.po.Permission;
import com.p2p.user.po.RolePermission;
import com.p2p.user.service.PermissionService;
import com.p2p.user.service.RolePermissionService;
import com.p2p.user.vo.PermissionVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Allen on 2017/3/19.
 */
@RestController
@RequestMapping(value = "permission")
public class PermissionController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(PermissionController.class);
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RolePermissionService rolePermissionService;


    @RequestMapping(value = "selectPermissionTree", method = RequestMethod.GET)
    public Message selectPermissionTree(HttpServletRequest request) {
        List<PermissionVo> permissionVoList = permissionService.selectPermissionVo();
        permissionVoList.stream().forEach(permissionVo -> {
            if (permissionVo.getType() == 1) {
                permissionVo.setChecked(true);
                permissionVo.setChkDisabled(true);
            }
        });
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), permissionVoList);
    }


    @RequestMapping(value = "selectPermission", method = RequestMethod.GET)
    public Map selectPermission(HttpServletRequest request) {

        List<Permission> permissionList = permissionService.selectList(new EntityWrapper<Permission>().eq("status", 1));
        Map result = new HashMap();
        result.put("rel", true);
        result.put("msg", "SUCCESS");
        result.put("list", permissionList);
        result.put("count", permissionList.size());
        return result;
    }


    /**
     * 根据父节点获取子节点权限
     *
     * @return
     */
    @RequestMapping(value = "selectPermissionByParentCode", method = RequestMethod.GET)
    public List selectPermissionByParentCode(HttpServletRequest request) {
        String parentCode = request.getParameter("parentCode");
        Long roleId = getRoleId();
        CacheManager cacheManager = CacheManager.getInstance();
        List<Permission> permissions = (List<Permission>) cacheManager.getCache(roleId);
        if (permissions == null) {
            permissions = permissionService.selectPermissionByRoleId(getRoleId());
            cacheManager.addCache(roleId, permissions);
        }
        Permission permissionParent = permissions.stream().filter(permission -> permission.getPermissionCode().equals(parentCode)).collect(Collectors.toList()).get(0);
        List result = new ArrayList();
        permissions.stream().filter(permission -> permission.getParentId() == permissionParent.getId()).sorted(Comparator.comparing(Permission::getSorting).reversed()).forEach(permission -> {
            Map map = new HashMap();
            map.put("title", permission.getName());
            map.put("icon", permission.getIcon());
            map.put("spread", false);
            map.put("href", permission.getPermissionUrl());
            result.add(map);
        });
        return result;
    }


    /**
     * 修改角色权限
     *
     * @return
     */
    @RequestMapping(value = "updatePermissionByRoleId", method = RequestMethod.POST)
    public Message updatePermissionByRoleId(HttpServletRequest request) {
        Long roleId = Long.parseLong(request.getParameter("roleId"));
        String ids = request.getParameter("ids");
        List<RolePermission> list = new ArrayList();
        Arrays.asList(ids.split(",")).forEach(s -> {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setPermissionId(Long.parseLong(s));
            rolePermission.setRoleId(roleId);
            rolePermission.setCreateTime(new Timestamp(System.currentTimeMillis()));
            rolePermission.setStatus(1);
            list.add(rolePermission);
        });
        rolePermissionService.delete(new EntityWrapper<RolePermission>().eq("role_id", roleId));
        rolePermissionService.insertBatch(list);
        CacheManager cacheManager = CacheManager.getInstance();
        cacheManager.removeCache(roleId);

        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }


    /**
     * 增加新权限
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "insertPermission", method = RequestMethod.POST)
    public Message insertPermission(HttpServletRequest request, Permission permission) {

        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        permission.setCreateTime(timestamp);
        permission.setStatus(1);
        permissionService.insert(permission);
        CacheManager cacheManager = CacheManager.getInstance();
        cacheManager.clearCache();
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }


    /**
     * 获取用户 By UserId
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectPermissionById", method = RequestMethod.GET)
    public Message selectPermissionById(HttpServletRequest request) {

        Long permissionId = Long.parseLong(request.getParameter("permissionId"));
        Permission permission = permissionService.selectOne(new EntityWrapper<Permission>().eq("id", permissionId));
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg(), permission);
    }


    /**
     * 更新权限信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "updatePermission", method = RequestMethod.POST)
    public Message updatePermission(HttpServletRequest request, Permission permission) {

        permissionService.updateById(permission);
        CacheManager cacheManager = CacheManager.getInstance();
        cacheManager.clearCache();
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }


    /**
     * 删除权限
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "deletePermission", method = RequestMethod.GET)
    public Message deletePermission(HttpServletRequest request) {
        Long permissionId = Long.parseLong(request.getParameter("permissionId"));
        Permission permission = permissionService.selectOne(new EntityWrapper<Permission>().eq("id", permissionId));
        permission.setStatus(-1);
        permissionService.updateById(permission);
        return new Message(ResponseEnum.SUCCESS.getCode(), ResponseEnum.SUCCESS.getMsg());
    }


    /**
     * 分页获取权限
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "selectPermissionPage", method = RequestMethod.GET)
    public ResMessage<Permission> selectPermissionPage(HttpServletRequest request) {
        String pageIndex = ParamUtils.getParameter(request, "pageIndex");
        String pageSize = ParamUtils.getParameter(request, "pageSize");
        String sort = ParamUtils.getParameter(request, "sort");
        String order = ParamUtils.getParameter(request, "order");

        Page<Permission> page = null;
        if (StringUtils.isEmpty(sort)) {
            page = new Page<Permission>(StringUtils.stringToInt(pageIndex), StringUtils.stringToInt(pageSize));
        } else {
            page = new Page<Permission>(StringUtils.stringToInt(pageIndex), StringUtils.stringToInt(pageSize),
                    sort);
            page.setAsc(PageUtil.isAsc(order));
        }
        EntityWrapper<Permission> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("status", 1);
        logger.info(page.toString());
        page = permissionService.selectPage(page, entityWrapper);
        logger.info(page.toString());
        logger.info(page.getTotal() + "");
        return new ResMessage<>(page.getRecords(), ResponseEnum.SUCCESS.getMsg(), true, page.getTotal());
    }
}

